package com.swn.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SignUtil {

	/**
	 * map 排序
	 * 
	 * @param unsortMap
	 * @return sortMap
	 */
	private static Map<String, String> sortMap(Map<String, String> unsortMap) {
		Map sortedMap = new TreeMap();
		sortedMap.putAll(unsortMap);
		return sortedMap;
	}

	/**
	 * 参数Map转成Str
	 * 
	 * @param params
	 * @param charset
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String paramToQueryString(Map<String, String> params,
			String charset) throws UnsupportedEncodingException {
		if ((params == null) || (params.size() == 0)) {
			return null;
		}
		StringBuilder paramString = new StringBuilder();
		boolean first = true;
		for (Map.Entry p : params.entrySet()) {
			String key = String.valueOf(p.getKey());
			String val = String.valueOf(p.getValue());
			if (!(first)) {
				paramString.append("&");
			}
			paramString.append(key);
			if (val != null) {
				String valStr = urlEncode(val, charset);
				paramString.append("=").append(valStr);
			}
			first = false;
		}
		return paramString.toString();
	}
	/**
	 * 参数编码
	 * 
	 * @param value
	 * @param charset
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String urlEncode(String value, String charset)
			throws UnsupportedEncodingException {
		if (value == null) {
			return null;
		}
		String encodeStr = URLEncoder.encode(value, charset);
		encodeStr = encodeStr.replace("+", "%20");
		encodeStr = encodeStr.replace("*", "%2A");
		encodeStr = encodeStr.replace("%7E", "~");
		return encodeStr;
	}

	
	public static Map<String, String> stringToMap(String param) {
		if (param == null) {
			return null;
		}
		try {
			param = URLDecoder.decode(param, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String[] strs = param.split("&&");
		Map<String, String> params = new HashMap<String, String>();
		for (String str : strs) {
			String[] s = str.split("=");
			if ("msgTypeId".equals(s[0])) {
				params.put("msgTypeId", s[1]);
			}
			if ("receiverUserId".equals(s[0])) {
				params.put("receiverUserId", s[1]);
			}
			if ("senderId".equals(s[0])) {
				params.put("senderId", s[1]);
			}
			if ("content".equals(s[0])) {
				params.put("content", s[1]);
			}
		}
		return params;

	}
	public static void main(String[] args) {
		String str = "msgTypeId=即时消息&&receiverUserId=40386&&content=Hello,World!!!&&senderId=admin";
	}
}
